//
//  FMManager.m
//  NLine
//
//  Created by weixian he on 12-8-29.
//  Copyright (c) 2012年 . All rights reserved.
//

#import "FMManager.h"

#import "SingletonDefine.h"
#import "SFHFKeychainUtils.h"
#import "InterfaceDefine.h"
#import "MyDataObject.h"
#import "JSONKit.h"

#define kPersonalMessageFile (@"personalMessage.txt")
#define PATH_OF_DOCUMENT    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

@interface FMManager()
{
    
}

@end

@implementation FMManager
@synthesize isLogin,isModel;
@synthesize userId,modeIdentify,heaerPicName,userPhotoName;
@synthesize updateInboxCtrl,updateMsgCtrl,updateSecondCtrl,slideBarHideFlag;
@synthesize personalFriendLists;
@synthesize firstMenuItemFlag,secondMenuItemFlag;

static FMManager *instace = nil;
GTMOBJECT_SINGLETON_BOILERPLATE(FMManager, sharedInstance)

- (void)dealloc
{
    self.personalFriendLists = nil;
    self.userId = nil;
    self.modeIdentify = nil;
    self.firstMenuItemFlag = nil;
    self.secondMenuItemFlag = nil;
    self.heaerPicName = nil;
    self.userPhotoName = nil;
    [super dealloc];
}

-(void)initData
{
    self.isLogin = NO;
    NSString *name = [SFHFKeychainUtils getPasswordForUsername:@"ismodel" andServiceName:kAppName error:nil];
    if(name && [name isEqualToString:@"YES"])
    {
        self.isModel = YES;
    }
    else {
        self.isModel = NO;
    }
    
    self.updateMsgCtrl = FALSE;
    self.updateInboxCtrl = FALSE;
    self.updateSecondCtrl = FALSE;
    
    self.slideBarHideFlag = YES;
    
    self.firstMenuItemFlag = [[[KeyValueObject alloc] init] autorelease];
    self.firstMenuItemFlag.key = @"0";
    self.firstMenuItemFlag.keyDispName = @"首页";
    self.secondMenuItemFlag = @"121";
    
    NSString *tempUserId = [SFHFKeychainUtils getPasswordForUsername:kUserid andServiceName:kAppName error:nil];
    if(tempUserId)
    {
        self.userId = tempUserId;
    }
    
    NSString *temp;
    temp = [SFHFKeychainUtils getPasswordForUsername:kModeIdentify andServiceName:kAppName error:nil];
    if(temp)
    {
        self.modeIdentify = temp;
    }
    
    self.userPhotoName = [SFHFKeychainUtils getPasswordForUsername:kUserPhotoName andServiceName:kAppName error:nil];
    
    DLog(@"userId = %@, modeIdentify = %@,photoName:%@",self.userId,self.modeIdentify,self.userPhotoName);
}

+(void)showAlertView:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
    [alertView show];
    [alertView release];
}

+(void)showAlertViewTitle:(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
    [alertView show];
    [alertView release];
}

+(void)showAlertViewTitle:(NSString *)title message:(NSString *)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
    [alertView show];
    [alertView release];
}

//保存个人资料
+ (void)savePersonalMessageToLocal:(NSString *)json
{
    NSString *documentPath = [NSString stringWithFormat:@"%@/weimo",PATH_OF_DOCUMENT];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (result)
    {
        NSString *filePath = [documentPath stringByAppendingPathComponent:kPersonalMessageFile];
        result = [json writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

//获取个人资料
+ (NSString *)getPersonalMessageFromLocal
{
    NSString *filePath = [NSString stringWithFormat:@"%@/weimo",PATH_OF_DOCUMENT];
    filePath = [filePath stringByAppendingPathComponent:kPersonalMessageFile];
    NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    return fileContent;
}

//判断是否删除个人资料
+ (void)deletePersonalMessageOfLocal:(NSString *)loginUserId
{
    NSString *filePath = [NSString stringWithFormat:@"%@/weimo",PATH_OF_DOCUMENT];
    filePath = [filePath stringByAppendingPathComponent:kPersonalMessageFile];
    NSString *contentString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (!contentString || contentString.length == 0)
    {
        return;
    }
    
    NSDictionary *dicRe = [contentString objectFromJSONString];
    NSString *oldLoginUserId = [NSString stringWithFormat:@"%@",[dicRe objectForKey:@"userId"]];
    
    DLog(@"id new:%@,old:%@",loginUserId,oldLoginUserId);
    
    if (![oldLoginUserId isEqualToString:loginUserId])
    {
        NSString *documentPath = [NSString stringWithFormat:@"%@/weimo",PATH_OF_DOCUMENT];
        NSString *filePath = [documentPath stringByAppendingPathComponent:kPersonalMessageFile];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
    else
    {
        NSNumber *modelsId =[dicRe objectForKey:@"modelsId"];
        if(modelsId)
        {
            NSString *documentPath = [NSString stringWithFormat:@"%@/weimo",PATH_OF_DOCUMENT];
            NSString *filePath = [documentPath stringByAppendingPathComponent:kPersonalMessageFile];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:filePath error:nil];

        }
    }
}

#pragma mark - protected methods

-(void)releaseData
{
    self.userId = nil;
    self.modeIdentify = nil;
    self.heaerPicName = nil;
}

//设置slideBarHideFlag
- (void)setSlideBarHideFlagWithBoolValue:(BOOL)flag
{
    self.slideBarHideFlag = flag;
}

//根据parentId获取目录数据
+ (NSMutableArray *)getMenuDatasOfChoosedFirstMenu:(NSString *)parentId
{
    NSMutableArray *secondArray = [[NSMutableArray alloc] init];
    NSString *file = [[NSBundle mainBundle] pathForResource:@"mode_sidebar" ofType:@"json"];
    NSString *string = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *result = [string objectFromJSONString];
    NSString *status = [result objectForKey:@"status"];
    
    if ([status isEqualToString:@"200"])
    {
        NSArray *array = [result objectForKey:@"array"];
        for (int i=0; i<array.count; i++)
        {
            NSDictionary *dic = [array objectAtIndex:i];
            NSString *parentIdStr = [dic objectForKey:@"parentId"];
            if ([parentIdStr isEqualToString:parentId])
            {
                [secondArray addObject:dic];
            }
        }
    }
    
    return [secondArray autorelease];
}

//获取id相对应的name
+ (NSString *)getMenuNameOfId:(NSString *)selfId
{
    NSString *queryResult = @"";
    
    NSString *file = [[NSBundle mainBundle] pathForResource:@"mode_sidebar" ofType:@"json"];
    NSString *string = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *result = [string objectFromJSONString];
    NSString *status = [result objectForKey:@"status"];
    
    if ([status isEqualToString:@"200"])
    {
        NSArray *array = [result objectForKey:@"array"];
        for (int i=0; i<array.count; i++)
        {
            NSDictionary *dic = [array objectAtIndex:i];
            NSString *selfIdStr = [dic objectForKey:@"selfId"];
            if ([selfIdStr isEqualToString:selfId])
            {
                queryResult = [dic objectForKey:@"name"];
            }
        }
    }
    
    return queryResult;
}

//刷新私信列表<MyDataObject>
- (void)refreshPersonalFriendListDatas:(NSArray *)array
{
    self.personalFriendLists = [[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i<array.count; i++)
    {
        NSDictionary *dic = [array objectAtIndex:i];
        MyDataObject *item = [[MyDataObject alloc] init];
        item.value1 = [dic objectForKey:@"fromUserid"];
        item.value2 = [dic objectForKey:@"modelsName"];
        item.value3 = [dic objectForKey:@"modelsAvatarstrUrl"];
        item.value3 = [NSString stringWithFormat:@"small_%@",item.value3];
        item.value4 = [dic objectForKey:@"lastPostMessages"];
        item.value5 = [dic objectForKey:@"lastSendTime"];
        item.value6 = [dic objectForKey:@"unreadPage"];
        [self.personalFriendLists addObject:item];
        [item release];
    }
}

@end